<template>
  <section class="padding EndWaybillList">
    <el-card>
      <el-form
        :inline="true"
        :model="searchCriteria"
        class=" padding-top-sm "
        size="mini"
      >
        <el-row>
          <el-col :span="10">
            <el-form-item label="运单号">
              <el-input
                v-model="waybillNoStr"
                type="textarea"
                placeholder="运单号"
              />
            </el-form-item>
            <el-form-item label="参考号">
              <el-input
                v-model="referenceNoStr"
                type="textarea"
                placeholder="运单号"
              />
            </el-form-item>
            <el-form-item label="主单号">
              <el-input
                v-model="masterNumberStr"
                type="textarea"
                placeholder="主单号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="下单时间">
              <el-date-picker
                v-model="earchTimer"
                type="datetimerange"
                align="right"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['12:00:00', '12:00:00']"
                value-format="yyyy-MM-dd HH:mm:ss"
                :picker-options="pickerOptions"
              />
            </el-form-item>
            <div class="form-inline">
              <el-form-item label="起运港">
                <el-select
                  v-model="shipmentPort"
                  filterable
                  placeholder="请选择"
                >
                  <el-option-group
                    v-for="group in options"
                    :key="group.label"
                    :label="group.label"
                  >
                    <el-option
                      v-for="itme in group.options"
                      :key="itme.value"
                      :label="itme.label"
                      :value="itme.value"
                    />
                  </el-option-group>
                </el-select>
              </el-form-item>
              <el-form-item label="目的港">
                <el-select
                  v-model="destinationPort"
                  filterable
                  placeholder="请选择"
                >
                  <el-option-group
                    v-for="group in options"
                    :key="group.label"
                    :label="group.label"
                  >
                    <el-option
                      v-for="itme in group.options"
                      :key="itme.value"
                      :label="itme.label"
                      :value="itme.value"
                    />
                  </el-option-group>
                </el-select>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="4" class="text-right">
            <el-form-item>
              <el-button type="primary" @click="onSubmit">查询</el-button>
              <el-button type="primary" @click="onReset">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="form-inline" />
        <div />
      </el-form>
    </el-card>

    <el-card class="margin-top">
      <div class=" padding-bottom-sm flex justify-between">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[20, 40, 60, 80, 100]"
          :page-size="pageSize"
          layout="prev, pager, next, jumper, sizes,total"
          :total="pageTotal"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <!-- <el-button-group>
          <el-button type="primary" size="mini" @click="bacthImportData"
            >批量导入打单数据并获取标签</el-button
          >
        </el-button-group> -->
      </div>
      <el-table
        class="table-box"
        :border="true"
        :data="tableData"
        style="width: 100%"
        size="mini"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <!-- <el-table-column type="index" label="序号" /> -->
        <!-- 遍历col -->
        <ex-table-column
          v-for="col in tableColumns"
          :key="col.prop"
          :auto-fit="true"
          :fit-header="true"
          :prop="col.prop"
          :label="col.label"
        >
          <template slot-scope="scope">
            <template v-if="col.prop === 'customerTotalPackages'">
              <div @click="getTag(scope.row)">
                <el-link class="text-sm">{{
                  scope.row['customerTotalPackages']
                }}</el-link>
              </div>
            </template>
            <template v-else-if="col.prop === 'creator'">
              <el-popover placement="left" trigger="hover">
                <div>
                  <div class="padding-sm">打单日志</div>
                  <div>{{ scope.row['sysRemark'] || '空' }}</div>
                </div>

                <i slot="reference" class="el-icon-s-order text-xl" />
              </el-popover>
            </template>
            <template v-else-if="col.prop === 'status'">
              {{
                $t(`waybill.${publicData.waybillStatusMap[scope.row.status]}`)
              }}
            </template>
            <div v-else v-html="scope.row[col.prop]" />
          </template>
        </ex-table-column>

        <el-table-column
          :auto-fit="true"
          fixed="right"
          label="操作"
          width="140"
        >
          <template slot-scope="scope">
            <div class="flex align-center">
              <el-tooltip
                class="item margin-left-xs"
                effect="dark"
                content="查看订单详情"
                placement="top"
              >
                <i
                  class="el-icon-zoom-in operation-icon text-xl"
                  @click="colCheckDetails(scope.row)"
                />
              </el-tooltip>
              <el-tooltip
                v-if="scope.row.status <= 80 && scope.row.palceOrderWay != 2"
                class="item margin-left-xs"
                effect="dark"
                content="编辑"
                placement="top"
              >
                <i
                  class="el-icon-edit-outline operation-icon  text-xl"
                  @click="colEdit(scope.row)"
                />
              </el-tooltip>

              <el-tooltip
                v-if="
                  (scope.row.labelStatus == 2 &&
                    scope.row.palceOrderWay == 2) ||
                    (scope.row.status <= 80 && scope.row.palceOrderWay != 2)
                "
                class="item margin-left-xs"
                effect="dark"
                content="删除"
                placement="top"
              >
                <i
                  class="el-icon-close text-red operation-icon text-xl"
                  @click="colDel(scope.row)"
                />
              </el-tooltip>

              <el-tooltip
                v-if="
                  scope.row.labelStatus < 99 && scope.row.palceOrderWay == 2
                "
                class="item margin-left-xs"
                effect="dark"
                content="再次推送"
                placement="top"
              >
                <i
                  class="el-icon-s-promotion text-blue operation-icon text-xl"
                  @click="helperOperate(scope.row)"
                />
              </el-tooltip>

              <el-tooltip
                v-if="
                  scope.row.labelStatus >= 99 && scope.row.palceOrderWay == 2
                "
                class="item margin-left-xs"
                effect="dark"
                content="下载标签"
                placement="top"
              >
                <i
                  class="el-icon-close operation-icon"
                  @click="exportTrackNumber(scope.row)"
                />
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <HdWaybillSubs :id="waybillId" :show-subs.sync="showSubs" />
  </section>
</template>

<script>

import HdWaybillSubs from './components/HdWaybillSubs'
import { mapGetters } from 'vuex'
import { timeLimit } from '@/utils/validate'
import { compileStr } from '@/utils'
import {
  listPage,
  deleteWaybillHdById,
  againSendExpressLabel
} from '@/api/endpoint'

export default {
  name: 'EndWaybillList',
  components: {
    HdWaybillSubs
  },
  computed: {
    ...mapGetters(['publicData'])
  },
  data() {
    return {
      pickerOptions: timeLimit(),
      waybillId: 0,
      showSubs: false,
      options: [],
      currentPage: 1,
      pageSize: 20,
      pageTotal: 0,
      earchTimer: [],
      masterNumberStr: '',
      waybillNoStr: '',
      referenceNoStr: '',
      destinationPort: '',
      shipmentPort: '',
      searchCriteria: {
        startCdate: '',
        endCdate: '',
        destinationPort: '',
        shipmentPort: '',
        waybillNo: [],
        masterNumber: [],
        referenceNo: [],
        countryId: '',
        hdType: ''
      },
      tableColumns: [
        { prop: 'waybillNo', label: '运单号' },
        { prop: 'statusName', label: '状态' },
        { prop: 'masterNumber', label: '主单号' },
        { prop: 'referenceNo', label: '参考号' },
        { prop: 'waybillSingleNo', label: '分单号' },
        { prop: 'subReferenceNo', label: '参考号' },
        { prop: 'status', label: '状态' },
        { prop: 'subActualWeight', label: '重量' },
        { prop: 'subVolume', label: '体积' },
        { prop: 'subTotalPackages', label: '件数' },
        { prop: 'customerActualWeight', label: '总实重' },
        { prop: 'customerVolume', label: '总体积' },
        { prop: 'customerTotalPackages', label: '总件数' },
        { prop: 'shipmentPortName', label: '起运港' },
        { prop: 'destinationPortName', label: '目的港' },
        { prop: 'palceOrderWayName', label: '渠道' },
        { prop: 'cdate', label: '下单时间' },
        { prop: 'creator', label: '其他' }
      ],
      tableData: []
    }
  },
  mounted() {
    this.init()

    if (this.$route.query.waybillNo) {
      this.searchCriteria.waybillNo = this.$route.query.waybillNo
    }
    if (this.$route.query.referenceNo) {
      this.searchCriteria.referenceNo = this.$route.query.referenceNo
    }

    this.queryList()
  },
  methods: {
    init() {
      const port = []
      const airPort = []
      if (this.publicData.portMap) {
        for (var key in this.publicData.portMap) {
          port.push({
            value: '0-' + key,
            label: this.publicData.portMap[key]
          })
        }
      }
      if (this.publicData.airPortMap) {
        for (var key in this.publicData.airPortMap) {
          airPort.push({
            value: '1-' + key,
            label: this.publicData.airPortMap[key]
          })
        }
      }
      this.options.push({
        label: '海运',
        options: port
      })
      this.options.push({
        label: '空运',
        options: airPort
      })
    },

    async queryList() {
      this.searchCriteria.pageSize = this.pageSize
      this.searchCriteria.currentPage = this.currentPage

      if (this.earchTimer.length > 0) {
        this.searchCriteria.startCdate = this.earchTimer[0]
        this.searchCriteria.endCdate = this.earchTimer[1]
      } else {
        this.searchCriteria.startCdate = ''
        this.searchCriteria.endCdate = ''
      }
      console.log('masterNumberStr', this.masterNumberStr.indexOf('\n'))
      if (this.masterNumberStr && this.masterNumberStr.indexOf('\n')) {
        this.searchCriteria.masterNumber = this.masterNumberStr.split('\n')
      } else {
        this.searchCriteria.masterNumber = null
      }
      if (this.waybillNoStr && this.waybillNoStr.indexOf('\n')) {
        this.searchCriteria.waybillNo = this.waybillNoStr.split('\n')
      } else {
        this.searchCriteria.waybillNo = null
      }
      if (this.referenceNoStr && this.referenceNoStr.indexOf('\n')) {
        this.searchCriteria.referenceNo = this.referenceNoStr.split('\n')
      } else {
        this.searchCriteria.referenceNo = null
      }
      // let isSea = -1;
      // let isAir = -1;
      if (this.destinationPort) {
        const dport = this.destinationPort.split('-')
        this.searchCriteria.destinationPort = dport[1]
        this.searchCriteria.hdType = dport[0]
        // isSea = dport[0];
      }

      if (this.shipmentPort) {
        const dport = this.shipmentPort.split('-')
        this.searchCriteria.shipmentPort = dport[1]
        this.searchCriteria.hdType = dport[0]
        // isAir = dport[0];
      }
      // if(isSea != -1 && isAir != -1 && isSea != isAir) {
      //     this.$message.error("起运港和目的港必须同时为海运或者空运");
      //     return;
      // }

      console.log('searchCriteria', this.searchCriteria)
      const list = await listPage(this.searchCriteria)

      for (const i in list.subData) {
        for (const j of list.datas) {
          switch (j.palceOrderWay) {
            case 0:
              j.palceOrderWayName = '清关+派送'
              break
            case 1:
              j.palceOrderWayName = '清关'
              break
            case 2:
              j.palceOrderWayName = '快递派送'
              break
            case 3:
              j.palceOrderWayName = '卡车派送'
              break
          }
          if (parseInt(j.id) === parseInt(i)) {
            j.waybillSingleNo = ''
            j.subReferenceNo = ''
            j.subStatus = ''
            j.subActualWeight = ''
            j.subVolume = ''
            j.subTotalPackages = ''
            for (const k of list.subData[i]) {
              j.waybillSingleNo += `<div>${k.waybillNo}</div>`
              j.subReferenceNo += `<div>${k.referenceNo}</div>`
              j.subStatus += `<div>${
                k.status
                  ? this.$t(`waybill.${publicData.waybillStatusMap[k.status]}`)
                  : ''
              }</div>`
              j.subActualWeight += `<div>${k.customerActualWeight}</div>`
              j.subVolume += `<div>${k.customerVolume}</div>`
              j.subTotalPackages += `<div>${k.customerTotalPackages}</div>`
            }
          }
        }
      }

      console.log('list.datas :>> ', list.datas)
      this.tableData = list.datas
      this.pageTotal = list.count

      const airMap = this.publicData.airPortMap
      const seaMap = this.publicData.portMap
      const statusMap = this.publicData.waybillStatusMap

      for (const i of this.tableData) {
        switch (i.palceOrderWay) {
          case 0:
            i.palceOrderWayName = '清关+派送'
            break
          case 1:
            i.palceOrderWayName = '清关'
            break
          case 2:
            i.palceOrderWayName = '快递派送'
            break
          case 3:
            i.palceOrderWayName = '卡车派送'
            break
        }

        if (i.hdType == 0) {
          if (i.shipmentPort) {
            i.shipmentPortName = seaMap[i.shipmentPort]
          }
          if (i.destinationPort) {
            i.destinationPortName = seaMap[i.destinationPort]
          }
        } else {
          if (i.shipmentPort) {
            i.shipmentPortName = airMap[i.shipmentPort]
          }
          if (i.destinationPort) {
            i.destinationPortName = airMap[i.destinationPort]
          }
        }

        if (i.status) {
          i.statusName = this.$t('waybill.' + statusMap[i.status])
        }
      }

      this.$store.dispatch('app/toggleDialog', false)
    },

    onSubmit() {
      this.$store.dispatch('app/toggleDialog', true)
      this.queryList()
    },
    onReset() {
      this.$store.dispatch('app/toggleDialog', true)
      this.earchTimer = []
      this.masterNumberStr = ''
      this.waybillNoStr = ''
      this.referenceNoStr = ''
      this.destinationPort = ''
      this.shipmentPort = ''
      this.searchCriteria = {
        startCdate: '',
        endCdate: '',
        destinationPort: '',
        shipmentPort: '',
        waybillNo: [],
        masterNumber: [],
        referenceNo: [],
        countryId: ''
      }
      this.queryList()
    },
    handleSizeChange(val) {
      this.$store.dispatch('app/toggleDialog', true)
      this.pageSize = val
      this.queryList()
    },
    handleCurrentChange(val) {
      this.$store.dispatch('app/toggleDialog', true)
      this.currentPage = val
      this.queryList()
    },

    colCheckDetails(row) {
      this.$router.push({
        name: 'WaybillHdDetail',
        params: { id: compileStr(row.id.toString()) }
      })
    },
    colEdit(row) {
      // row.hdType  == 0 =》海运编辑
      // 海运
      let pathName = 'endOrderToShipping'
      if (row.hdType) {
        // 空运
        pathName = 'endOrderToAirFreight'
      }
      this.$router.push({
        path: `/endWaybill/${pathName}`,
        query: { waybillId: row.id, palceOrderWay: row.palceOrderWay }
      })
    },
    colDel(row) {
      // 删除
      this.$confirm('确认删除？')
        .then(_ => {
          this.$store.dispatch('app/toggleDialog', true)
          deleteWaybillHdById({ id: row.id }).then(res => {
            if (res.code === 200) {
              this.$message({
                message: '已删除',
                type: 'success'
              })
              this.queryList()
            } else {
              this.$store.dispatch('app/toggleDialog', false)
              this.$message.error(res.message)
            }
          })
        })
        .catch(_ => {})
    },
    async helperOperate(row) {
      // 再次推送
      // const data = await saveSubDimensAndPrint()
      this.$confirm('推送后请稍等一会再查看日志是否成功，是否推送？')
        .then(_ => {
          this.$store.dispatch('app/toggleDialog', true)
          againSendExpressLabel({ id: row.id }).then(res => {
            if (res.code === 200) {
              this.$message({
                message: '已推送',
                type: 'success'
              })
            } else {
              this.$message.error(res.message)
            }
          })
          this.$store.dispatch('app/toggleDialog', false)
        })
        .catch(_ => {})
    },
    async exportTrackNumber(row) {
      // 下载标签
    },
    getTag(row) {
      this.showSubs = true
      this.waybillId = row.id
    },
    bacthImportData() {}
  }
}
</script>

<style scoped>
.EndWaybillList >>> .el-textarea__inner {
  min-height: 60px !important;
}
</style>
